package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.Item;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AmqpListener {

    @Autowired
    RestHighLevelClient client;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.insert_queue"),
            exchange = @Exchange(value = "item.topic", type = ExchangeTypes.TOPIC),
            key = {"item.insert"}
    ))
    public void listenInsert(String message) throws IOException {
        Item hotel = JSON.parseObject(message, Item.class);
        System.out.println("监听到新增数据，开始处理");
        System.out.println(hotel);

        IndexRequest request = new IndexRequest("item").id(hotel.getId().toString());
        request.source(JSON.toJSONString(hotel), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);

        System.out.println("处理完成");
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.delete_queue"),
            exchange = @Exchange(value = "item.topic", type = ExchangeTypes.TOPIC),
            key = {"item.delete"}
    ))
    public void listenDelete(String message) throws IOException {
        System.out.println("监听到删除数据，开始处理");
        System.out.println(message);

        DeleteRequest request = new DeleteRequest("item", message);
        client.delete(request, RequestOptions.DEFAULT);

        System.out.println("处理完成");
    }

}
